import "reflect-metadata";
import { existsSync } from "node:fs";
import { join } from "node:path";
import { makeAppWithSingleInstanceLock } from "@lib/electron-app/factories/app/instance";
import { makeAppSetup } from "@lib/electron-app/factories/app/setup";
import logger from "@shared/logger/main-logger";
import { app, ipcMain, shell } from "electron";
import { initMainBridge } from "./bridge";
import { isLinux } from "./constant";
import type { McpService } from "./services/mcp-service";
import type { ShortcutsService } from "./services/shortcuts-service";
import { container } from "./shared/bindings";
import { TYPES } from "./shared/types";
import { MainWindow } from "./windows/main";

// Direct IPC handler for emergency log directory access
ipcMain.handle("shell:openLogDirectory", async () => {
  try {
    const userData = app.getPath("userData");
    const logsDir = join(userData, "logs");

    if (!existsSync(logsDir)) {
      return { success: false, error: "Log directory does not exist" };
    }

    const result = await shell.openPath(logsDir);

    if (result) {
      // If there's an error message, opening failed
      return { success: false, error: result };
    }

    return { success: true };
  } catch (error) {
    logger.error("Direct shell handler: Error opening log directory", {
      error,
    });
    return {
      success: false,
      error: error instanceof Error ? error.message : "Unknown error",
    };
  }
});

makeAppWithSingleInstanceLock(async () => {
  // If it is linux, force enable hardware acceleration and GPU rendering globally
  if (isLinux) {
    app.commandLine.appendSwitch("enable-gpu-rasterization");
    app.commandLine.appendSwitch("enable-zero-copy");
    app.commandLine.appendSwitch("disable-gpu-sandbox");
    app.commandLine.appendSwitch("enable-hardware-overlays");
    app.commandLine.appendSwitch(
      "enable-features",
      "VaapiVideoDecoder,VaapiIgnoreDriverChecks",
    );
    app.commandLine.appendSwitch("use-gl", "desktop");
    app.commandLine.appendSwitch("enable-accelerated-2d-canvas");
    app.commandLine.appendSwitch("enable-gpu-memory-buffer-video-frames");
  }

  await app.whenReady();
  await makeAppSetup(MainWindow);
  await initMainBridge();

  // Cleanup services on app quit
  app.on("will-quit", () => {
    try {
      // Cleanup shortcuts service
      const shortcutsService = container.get<ShortcutsService>(
        TYPES.ShortcutsService,
      );
      shortcutsService.cleanup();
    } catch {
      // Service might not be initialized
    }

    try {
      // Cleanup MCP service
      const mcpService = container.get<McpService>(TYPES.McpService);
      mcpService.cleanupMcpService();
    } catch {
      // Service might not be initialized
    }
  });
});
